#include "main.h"
#include "myapplication.h"
#include "MemoryLeakChecker.h"
#include "LoadLua.h"

void CleanUpUponExit(void)
{
	myApplication::getInstance()->Drop();
}

void changeSize(int w, int h) {
	myApplication::getInstance()->changeSize(w,h);
}

void renderScene(void) {
	myApplication::getInstance()->renderScene();
}

void SpecialInputKeyDown(int key, int x, int y) {
	myApplication::getInstance()->SpecialInputKeyDown(key,x,y);
}

void SpecialInputKeyUp(int key, int x, int y) {
	myApplication::getInstance()->SpecialInputKeyUp(key,x,y);
}

void KeyboardDown(unsigned char key, int x, int y){
	myApplication::getInstance()->KeyboardDown(key,x,y);
}

void KeyboardUp(unsigned char key, int x, int y){
	myApplication::getInstance()->KeyboardUp(key,x,y);
}

void MouseMove(int x, int y){
	myApplication::getInstance()->MouseMove(x,y);
}

void MouseClick(int button, int state, int x, int y){
	myApplication::getInstance()->MouseClick(button, state, x, y);
}

int main(int argc, char **argv )
{
	// memory leak checker
	CMemoryLeakChecker();

	lua_State *L = lua_open(); 

	// load the libs 
	luaL_openlibs(L); 

	if (luaL_loadfile(L, "config.lua") || lua_pcall(L, 0, 0, 0)) 
	{ 
		printf("error: %s\n", lua_tostring(L, -1)); 
		return -1; 
	}
	else
	{
		printf("Lua Config File Loaded\n");
	}

	lua_getglobal(L, "HIDE_MOUSE");
	lua_getglobal(L, "FULLSCREEN");
	lua_getglobal(L, "POSITION_X");
	lua_getglobal(L, "POSITION_Y");
	lua_getglobal(L, "PROGRAM_NAME");
	lua_getglobal(L, "SCREENWIDTH"); 
	lua_getglobal(L, "SCREENHEIGHT");

	bool HIDE_MOUSE = lua_toboolean(L, -7);
	bool FULLSCREEN = lua_toboolean(L, -6);
	int POSITION_X = (int)lua_tonumber(L, -5);
	int POSITION_Y = (int)lua_tonumber(L, -4);
	const char* PROGRAM_NAME = lua_tostring(L, -3);
	int SCREENWIDTH = (int)lua_tonumber(L, -2); 
	int SCREENHEIGHT = (int)lua_tonumber(L, -1);

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
	glutInitWindowPosition(POSITION_X, POSITION_Y);
	glutInitWindowSize(SCREENWIDTH,SCREENHEIGHT);
	glutCreateWindow(PROGRAM_NAME);

	if(FULLSCREEN)
		glutFullScreen();

	if(HIDE_MOUSE)
		glutSetCursor(GLUT_CURSOR_NONE);

	glutReshapeFunc(changeSize);

	glutDisplayFunc(renderScene);
	glutIdleFunc(renderScene);

	glutSpecialFunc(SpecialInputKeyDown);
	glutSpecialUpFunc(SpecialInputKeyUp);
	glutKeyboardFunc(KeyboardDown);
	glutKeyboardUpFunc(KeyboardUp);
	glutPassiveMotionFunc(MouseMove);
	glutMouseFunc(MouseClick);// for mouse click

	// Exit
	atexit( CleanUpUponExit );

	if (myApplication::getInstance()->Init() == true)
		glutMainLoop();
	else
	{
		printf("Error Initialising Program\n");
		return 1;
	}

	lua_close(L);
	return 0;

}